
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
import {generateUniqueString} from "@/utils/passwordUtil";
const db = cloud.database()
const _ = db.command

/**
 * 数据结构
 * @param ctx
 */
export default async function (ctx: FunctionContext) {
  /**
   * {
   *     "id": "",
   *     "_id": "",
   *     "parentId": "656046efae4c15cb26f245dd",
   *     "name": "菜单管理",
   *     "type": 1,
   *     "path": "",
   *     "component": "",
   *     "perms": "",
   *     "icon": "",
   *     "sortValue": 1,
   *     "status": 1,
   *     "parentName": "权限管理"
   * }
   */
  let body = {
    pid:ctx.body.parentId,
    name:ctx.body.name,
    type:ctx.body.type
  }
  /**
   * {
   *
   *   "pid": "0",//上级部门
   *   "name": "主题",//菜单名称
   *   "type": "ww"//菜单类型
   * }
   */
  //1.校验参数
  if (nw.util.isNull(body.name)){
    return fail("菜单名称不能为空")
  }
  if (nw.util.isNull(body.type)){
    return fail("菜单类型不能为空")
  }
  //2.校验菜单名称是否重复
  let count  = await nw.db.count({
    dbName:"permission",
    whereJson:{
      name:_.eq(body.name),
      deleted:0
    }
  })
  if (count>0){
    return fail("菜单名称重复")
  }
  //3.构建保存结构
  let code =await genCode()
  let data = {
    pid:body.pid,
    name:body.name,
    code:code,
    type:body.type,
    status:1,
    createTime:new Date(),
    updateTime:new Date(),
    deleted:0
  }
  if (nw.util.isNull(body.pid)||body.pid===0){
    data.pid="0"
  }
  //4.保存数据
  let res = await  nw.db.add({
    dbName:"permission",
    dataJson:data
  })
  if (nw.util.isNull(res)){
    return fail("新增失败")
  }
  return ok("新增成功")

}
async function genCode() {
  let code = ""
  while (true){
    code = generateUniqueString(6)
    let count = await nw.db.count({
      dbName:"permission",
      whereJson:{
        code:_.eq(code),
        deleted:0
      }
    })
    if (count===0){
      break
    }
  }
  return code
}
